package com.flight.trans.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.BuildConfig;
import com.flight.trans.R;
import com.flight.trans.adapter.EnterPortWarehousingDetailsAdapter;
import com.flight.trans.bean.EnterPortStorageBean;
import com.flight.trans.bean.EnterPortWarehousingDetailBean.EnterPortWarehousingData;
import com.flight.trans.bean.EnterPortWarehousingDetailBean.EnterPortWarehousingData.InwardStorageData;
import com.flight.trans.bean.UnusualBean;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnSheetItemClickListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.BottomDialog;
import com.flight.trans.view.dialog.StorageContainerDialog;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.edit.EditorActivity;
import com.flight.trans.view.edit.EditorOrderNoActivity;
import com.lzy.okgo.model.HttpParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 进港人入库
 */
public class EnterPortWarehousingDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private TextView mTvTitleName;
    private RecyclerView mRvContainer ;

    private Button mBtnBlankRecord ,// 空白记录
            mBtnSubmit ,//提交
            mBtnRevise;//修改

    private TextView mTvOperationInfo ;//操作

    private LinearLayout mLlTallyContainer ;//交接信息
    private TextView mTvFlightNo ,//航班号
            mTvRouteLine ,//航线
            mTvAta ,//实落时间
            mTvTallyManager ,//分拣库管
            mTvTallyTime ;//分拣时间

    private EnterPortWarehousingDetailsAdapter mWarehousingDetailsAdapter;

    private int mFlightID ;

    private EnterPortWarehousingData mEnterPortWarehousingData ;
    private List<InwardStorageData> mInwardStorageDataList ;
    private List<InwardStorageData> mSaveInwardStorageDataList ;

    private List<String> mDestinationList ;

    @Override
    protected int setContentView() {
        return R.layout.activity_enter_port_warehousing_details;
    }

    @Override
    protected void initView() {
        mLlContainer = findViewById(R.id.mLlContainer);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mRvContainer = findViewById(R.id.mRvContainer);
        mBtnBlankRecord = findViewById(R.id.mBtnBlankRecord);
        mBtnSubmit = findViewById(R.id.mBtnSubmit);
        mBtnRevise = findViewById(R.id.mBtnRevise);

        mTvOperationInfo = findViewById(R.id.mTvOperationInfo);

        mLlTallyContainer = findViewById(R.id.mLlTallyContainer);
        mTvFlightNo = findViewById(R.id.mTvFlightNo);
        mTvRouteLine = findViewById(R.id.mTvRouteLine);
        mTvAta = findViewById(R.id.mTvAta);
        mTvTallyManager = findViewById(R.id.mTvTallyManager);
        mTvTallyTime = findViewById(R.id.mTvTallyTime);
    }

    @Override
    protected void initData() {
        mFlightID = mBundle.getInt(Constant.FlightID);
        IsEditor = mBundle.getBoolean(Constant.IsEditor);

        ConstantInfo.UnusualIDList.clear();

        CommonUtils.setScreenContainerPaddingTop(mLlContainer);

        mTvTitleName.setText(getString(R.string.title_enter_port_warehousing));
        CommonUtils.onFinishTouch(mActivity , mLlContainer);
    }

    @Override
    protected void initConnect() {
        linked(true);
    }

    private void linked(boolean isFirst){
        valueParams = new HttpParams();
        valueParams.put(Constant.FlightID , mFlightID);

        NetworkUtils.getEnterPortWarehousingDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                mEnterPortWarehousingData = (EnterPortWarehousingData) body;

                if(isFirst) {
                    mInwardStorageDataList = mEnterPortWarehousingData.getInwardStorageData();

                    if(mInwardStorageDataList == null)
                        mInwardStorageDataList = new ArrayList<>();
                }else {
                    List<InwardStorageData> mDataList = mEnterPortWarehousingData.getInwardStorageData();
                    Map<String , InwardStorageData> mDataMap = new HashMap<>();
                    for (int i = 0; i < mDataList.size(); i++) {
                        mDataMap.put(mDataList.get(i).getOrderNo() , mDataList.get(i));
                    }

                    for (int i = 0; i < mInwardStorageDataList.size(); i++) {
                        if(mDataMap.get(mInwardStorageDataList.get(i).getOrderNo()) != null) {
                            mInwardStorageDataList.get(i).setInwardStorageDetailData(mDataMap.get(mInwardStorageDataList.get(i).getOrderNo()).getInwardStorageDetailData());
                            mInwardStorageDataList.get(i).setAnomalyCnt(mDataMap.get(mInwardStorageDataList.get(i).getOrderNo()).getAnomalyCnt());
                        }
                    }
                }

                initLocationData();
            }
        }, valueParams);
    }

    /**
     * 初始化数据
     */
    private void initLocationData(){
        mBtnBlankRecord.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnSubmit.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnRevise.setVisibility(IsEditor ? View.GONE : View.VISIBLE);
        mTvOperationInfo.setVisibility(IsEditor ? View.VISIBLE : View.GONE);

        // 初始化界面信息
        initWarehousingInfo();

        // 初始化列表信息
        initWarehousingAdapter();
    }

    /**
     * 初始化信息
     */
    private void initWarehousingInfo() {
        mTvFlightNo.setText(mEnterPortWarehousingData.getFlightNo());
        mTvRouteLine.setText(mEnterPortWarehousingData.getFlightCourseCode());
        mTvAta.setText(CommonUtils.getTimeNorm(mEnterPortWarehousingData.getAta()));

        mDestinationList = new ArrayList<>();
        String flightCourseCode = mEnterPortWarehousingData.getFlightCourseCode();
        String[] CourseList = flightCourseCode.split("-");
        for (int i = 0; i < CourseList.length; i++) {
            if(BuildConfig.Station.equals(CourseList[i]))
                break;

            mDestinationList.add(CourseList[i]);
        }

        if(TextUtils.isEmpty(mEnterPortWarehousingData.getDispatchUserName()) && TextUtils.isEmpty(mEnterPortWarehousingData.getDispatchTime())) {
            mLlTallyContainer.setVisibility(View.GONE);
        }else {
            mLlTallyContainer.setVisibility(View.VISIBLE);
        }

        mTvTallyManager.setText(mEnterPortWarehousingData.getDispatchUserName());
        mTvTallyTime.setText(CommonUtils.getTimeNorm(mEnterPortWarehousingData.getDispatchTime()));
    }

    /**
     * 初始化列表
     */
    private void initWarehousingAdapter(){
        sortList();

        mWarehousingDetailsAdapter = new EnterPortWarehousingDetailsAdapter(mActivity, mInwardStorageDataList, IsEditor);
        mWarehousingDetailsAdapter.setHasStableIds(true);
        mRvContainer.setAdapter(mWarehousingDetailsAdapter);
        mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

        mWarehousingDetailsAdapter.setOnTextClickListener(mItemTextClickListener);
        mWarehousingDetailsAdapter.setOnItemClickListener(new WarehousingItemClickListener());
    }

    /**
     * 条目点击事件
     */
    private class WarehousingItemClickListener extends OnItemClickListener{
        @Override
        public void onLongClick(View view, int position) {
            if(!mInwardStorageDataList.get(position).isSelect()){
                if(mInwardStorageDataList.get(position).isBlankRecord()){
                    AlertDialog.getInstance(mActivity)
                            .setContent(R.string.dialog_confirm_delete_blank)
                            .setConfirmButton(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteBlank(position);
                                }
                            }).show();
                }else {
                    ToastUtils.showToast(R.string.toast_item_not_blank);
                }
            }else {
                ToastUtils.showToast(R.string.toast_item_selected);
            }
        }
    }

    /**
     * 确认删除
     * @param position
     */
    private void deleteBlank(int position) {
        mInwardStorageDataList.remove(position);

        initWarehousingAdapter();
    }

    /**
     * 条目字段点击事件
     */
    private OnTextClickListener mItemTextClickListener = new OnTextClickListener() {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvDestination:
                    // 始发站
                    if(mDestinationList.size() > 1){
                        BottomDialog.getInstance(mActivity)
                                .addSheetItem(mDestinationList)
                                .setOnItemClickListener(new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        mInwardStorageDataList.get(position).setOrap(mDestinationList.get(which));
                                        initWarehousingAdapter();
                                    }
                                }).show();
                    }
                    break;
                case R.id.mTvRealCount:
                    // 实到件数
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mInwardStorageDataList.get(position).setRealNum(TextUtils.isEmpty(content) ? 0 : Integer.parseInt(content));
                            mInwardStorageDataList.get(position).setState(Constant.Be_Warehousing);
                            initWarehousingAdapter();
                        }
                    } , String.valueOf(mInwardStorageDataList.get(position).getRealNum()));
                    break;
                case R.id.mTvStorageArea :
                    // 存放区域
                    StorageContainerDialog.getInstance(mActivity)
                            .setContent(mInwardStorageDataList.get(position).getInwardStorageDetailData() , IsEditor)
                            .setConfirmButton(new StorageContainerDialog.OnConfirmClickListener() {
                                @Override
                                public void onClick(List<EnterPortStorageBean> contentList) {
                                    mInwardStorageDataList.get(position).setInwardStorageDetailData(contentList);
                                    mInwardStorageDataList.get(position).setState(Constant.Be_Warehousing);

                                    mWarehousingDetailsAdapter.updateAdapter(mInwardStorageDataList);
                                }
                            })
                            .show();
                    break;
                case R.id.mTvUnusualStatus :
                    // 异常状态
                    mIntent = new Intent(mActivity , UnusualListActivity.class);
                    mBundle = new Bundle();
                    mBundle.putBoolean(Constant.IsEditor , IsEditor);
                    mBundle.putInt(Constant.Position , position);
                    if(mInwardStorageDataList.get(position).isBlankRecord()){
                        mBundle.putInt(Constant.TurnType , 1);
                        UnusualBean unusualBean = new UnusualBean();
                        unusualBean.setData(mInwardStorageDataList.get(position).getAnomalyRecordVOList());
                        mBundle.putSerializable(Constant.INFO , unusualBean);
                    }else {
                        mBundle.putInt(Constant.TurnType , 0);
                        mBundle.putInt(Constant.Business_ID , mInwardStorageDataList.get(position).getInwardOrderId());
                    }
                    mBundle.putString(Constant.Key_Order_No , mInwardStorageDataList.get(position).getOrderNo());
                    mBundle.putInt(Constant.Source_Type , 1);
                    mIntent.putExtras(mBundle);
                    turnActForResult(mIntent);
                    break;
                case R.id.mBtnOperation:
                    // 操作
                    InwardStorageData detailsBean = mInwardStorageDataList.remove(position);
                    detailsBean.setSelect(!detailsBean.isSelect());

                    if(detailsBean.isSelect()){
                        mInwardStorageDataList.add(detailsBean);
                    }else {
                        mInwardStorageDataList.add(0 , detailsBean);
                    }

                    initWarehousingAdapter();
                    break;
                case R.id.mTvOrderNo:
                    // 运单单号
                    EditorOrderNoActivity.openActivity(mActivity, new EditorOrderNoActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mInwardStorageDataList.get(position).setOrderNo(content);
                            initWarehousingAdapter();
                        }
                    } , mInwardStorageDataList.get(position).getOrderNo());
                    break;
            }
        }
    };

    /**
     * 排序集合
     */
    private void sortList(){
        List<InwardStorageData> beWarehousingList = new ArrayList<>();
        List<InwardStorageData> inWarehousingList = new ArrayList<>();

        for (int i = 0; i < mInwardStorageDataList.size(); i++) {
            if(mInwardStorageDataList.get(i).getState() == Constant.Be_Warehousing){
                beWarehousingList.add(mInwardStorageDataList.get(i));
            }else {
                inWarehousingList.add(mInwardStorageDataList.get(i));
            }
        }

        beWarehousingList.addAll(inWarehousingList);
        mInwardStorageDataList = beWarehousingList ;
    }

    /**
     * 获取此次入库的集合
     * @return
     */
    private List<InwardStorageData> getSelectedDataList(){
        List<InwardStorageData> inWarehousingList = new ArrayList<>();


        for (int i = 0; i < mInwardStorageDataList.size(); i++) {
            if(mInwardStorageDataList.get(i).isSelect())
                inWarehousingList.add(mInwardStorageDataList.get(i));
        }

        return inWarehousingList;
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mBtnSubmit:
                // 提交
                if(mInwardStorageDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                if(IsSaveIng){
                    ToastUtils.showToast(R.string.toast_save_ing);
                    return;
                }

                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_submit_warehousing_info)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clickSubmit();
                            }
                        }).show();
                break;
            case R.id.mBtnRevise:
                // 修改
                if(mInwardStorageDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                IsEditor = true ;
                initLocationData();
                break;
            case R.id.mBtnBlankRecord:
                // 生成空白记录
                if(mInwardStorageDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                InwardStorageData detailsBean = new InwardStorageData();
                detailsBean.setOrderNo(CommonUtils.getTimeStamp());
                detailsBean.setState(Constant.Be_Warehousing);
                detailsBean.setNum(0);
                detailsBean.setRealNum(0);
                detailsBean.setBlankRecord(true);
                detailsBean.setOrap(mDestinationList.get(0));
                mInwardStorageDataList.add(0 ,detailsBean);
                initWarehousingAdapter();
                break;
            case R.id.mIbBack:
                onBackPressed();
                break;
        }
    }

    /**
     * 提交数据
     */
    private void clickSubmit() {
        mSaveInwardStorageDataList = new ArrayList<>();

        for (int i = 0; i < mInwardStorageDataList.size(); i++) {
            if(mInwardStorageDataList.get(i).isSelect()) {
                // 将选择入库的变成已入库
                mInwardStorageDataList.get(i).setState(Constant.In_Warehousing);

                if(mInwardStorageDataList.get(i).getInwardStorageDetailData() != null)
                    mInwardStorageDataList.get(i).getInwardStorageDetailData().remove(null);
                mSaveInwardStorageDataList.add(mInwardStorageDataList.get(i));
            }
        }
        mEnterPortWarehousingData.setInwardStorageData(mSaveInwardStorageDataList);

        IsSaveIng = true ;

        NetworkUtils.saveEnterPortWarehousingDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                IsSaveIng = false;
                CommonUtils.writeCrashLog("进港录改保存成功");
                ToastUtils.showToast(R.string.toast_submit_success);
                onFinish(Constant.RESULT_CODE);
            }

            @Override
            public void onError() {
                CommonUtils.writeCrashLog("进港录改保存失败");
                IsSaveIng = false;
            }
        }, JsonUtils.parseBeanToJson(mEnterPortWarehousingData));
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , ConstantInfo.IN_STORAGE_IN , mFlightID);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_CODE){
            mBundle = data.getExtras();
            mInwardStorageDataList.get(mBundle.getInt(Constant.Position)).setAnomalyRecordVOList(((UnusualBean)mBundle.getSerializable(Constant.INFO)).getData());
            mInwardStorageDataList.get(mBundle.getInt(Constant.Position)).setAnomalyCnt(((UnusualBean)mBundle.getSerializable(Constant.INFO)).getData().size());
            initWarehousingAdapter();
        } else if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_REFRESH_CODE){
            linked(false);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
